package com.lagou.handler;

import com.lagou.client.RpcRequest;
import com.lagou.client.RpcResponse;
import com.lagou.service.ServiceRegistry;
import com.lagou.service.impl.ZkServiceDiscovery;
import com.lagou.service.impl.ZkServiceRegistry;
import com.lagou.util.RpcDecoder;
import com.lagou.util.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
    // 需要先给服务端指定一个IP和port
//    private static  String serverAddress="127.0.0.1:8080";

//    // 服务注册类
//    private static ServiceRegistry serviceRegistry;

//    public NettyServer(String serverAddress, ServiceRegistry serviceRegistry) {
//        this.serviceRegistry = serviceRegistry;
//        this.serverAddress = serverAddress;
//    }

    //nettyServer的初始化
    public  static void startServer(String hostName,int port){
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup(8);
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new RpcDecoder(RpcRequest.class));//解码器
                            pipeline.addLast(new RpcEncoder(RpcResponse.class));//编码器
                            pipeline.addLast(new NettyServerHandler());//业务处理器
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(hostName, port).addListener(future -> {
                if(future.isSuccess()){
                    System.out.println("服务端启动成功，监听端口："+port);
                }
            });
//            channelFuture.channel().closeFuture().sync();
            // 获取服务器要绑定的地址和端口

//            ChannelFuture future = serverBootstrap.bind(hostName, port).sync();
            // 服务注册
            ZkServiceRegistry serviceRegistry = new ZkServiceRegistry();
            String serverAddress = hostName+":"+port;
            serviceRegistry.init();
            if (serviceRegistry != null){
                serviceRegistry.registry(serverAddress);
            }
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
